<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
			label-width="68px">
			<el-form-item label="车牌" prop="licensePlate">
				<el-input v-model="queryParams.licensePlate" placeholder="请输入车牌" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="司机" prop="driverName">
				<el-input v-model="queryParams.driverName" placeholder="请输入司机名称" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="开始地点" prop="startLocation">
				<el-input v-model="queryParams.startLocation" placeholder="请输入开始地点" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="结束地点" prop="endLocation">
				<el-input v-model="queryParams.endLocation" placeholder="请输入结束地点" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="时间">
				<el-date-picker v-model="daterangeStartTime" style="width: 240px" value-format="yyyy-MM-dd"
					type="daterange" range-separator="-" start-placeholder="开始日期"
					end-placeholder="结束日期"></el-date-picker>
			</el-form-item>
			<el-form-item label="状态" prop="useCarStatus">
				<el-select v-model="queryParams.useCarStatus" placeholder="请选择状态" clearable>
					<el-option v-for="dict in dict.type.use_car_status" :key="dict.value" :label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="mb8">
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>
		
		<el-empty description="暂无行程信息" v-if="queryParams.pageNum == 1 && applycarList.length == 0"></el-empty>
		<el-row v-else>
			<el-table v-loading="loading" :data="applycarList" :border="true">
				<el-table-column label="ID" width="50" align="center">
					<template slot-scope="scope">
						{{ scope.row.id }}
					</template>
				</el-table-column>
				<el-table-column label="路线" align="center" prop="transitPlaces">
					<template slot-scope="scope">
						{{ formatTransitPlaces(scope.row.startLocation, scope.row.endLocation, scope.row.transitPlace) }}
					</template>
				</el-table-column>
				<el-table-column label="时间" align="center" prop="startTime" width="260">
					<template slot-scope="scope">
						{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }} - {{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}
					</template>
				</el-table-column>
				<el-table-column label="可占座数" align="center" prop="remainderSeatNum" width="80px" />
				<el-table-column label="已占座数" align="center" prop="reserveSeatNum" width="80px" />
				<el-table-column label="状态" align="center" prop="useCarStatus" width="80px">
					<template slot-scope="scope">
						<dict-tag :options="dict.type.use_car_status" :value="scope.row.useCarStatus" />
					</template>
				</el-table-column>
				<el-table-column label="车辆id" align="center" prop="carId" v-if="false" />
				<el-table-column label="车牌" align="center" prop="licensePlate" width="100" />
				<el-table-column label="司机id" align="center" prop="driverId" v-if="false" />
				<el-table-column label="司机名称" align="center" prop="driverName" width="80" />
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-view" @click="jump(scope.row.id)"
							v-hasPermi="['usecar:details:query']">详情
						</el-button>
						<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateCarDriver(scope.row)"
							v-hasPermi="['bpmapply:applycar:edit']" v-if="scope.row.isUpdateStatus == 1 && (roles.includes('admin') || roles.includes('carAdmin'))">修改司机车辆
						</el-button>
						<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
							v-hasPermi="['bpmapply:applycar:edit']" v-if="scope.row.isUpdateStatus == 1">修改
						</el-button>
						<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
							v-hasPermi="['bpmapply:applycar:remove']" v-if="scope.row.isDelStatus == 1">取消
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
		</el-row>

		<!-- 添加或修改用车申请对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<el-form-item label="用车类型" prop="carUseType" v-if="false">
					<el-select v-model="form.carUseType" placeholder="请选择用车类型" :disabled="true">
						<el-option v-for="dict in dict.type.car_use_type" :key="dict.value" :label="dict.label"
							:value="dict.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="用车明细id" prop="detailsCarId" v-if="false">
					<el-input v-model="form.detailsCarId" placeholder="请输入用车明细id" />
				</el-form-item>
				<el-form-item label="车型名称" prop="carId" v-if="false">
					<treeselect v-model="form.carId" :options="carOptions" :show-count="true" placeholder="请输入车型名称" />
				</el-form-item>
				<el-form-item label="司机名称" prop="driverId" v-if="false">
					<treeselect v-model="form.driverId" :options="driverOptions" :show-count="true"
						placeholder="请输入司机名称" />
				</el-form-item>
				<el-form-item label="开始地点" prop="startLocation">
					<el-input v-model="form.startLocation" placeholder="请输入开始地点" :disabled="form.carUseType == 2" />
				</el-form-item>
				<el-form-item label="中转地点" prop="transitPlace">
					<el-tag :key="tag" v-for="tag in form.transitPlace" :disable-transitions="false" :closable="form.carUseType == 1" @close="handleClose(tag)">
						{{ tag }}
					</el-tag>
					<template v-if="form.carUseType == 1">
						<el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
						</el-input>
						<el-button v-else class="button-new-tag" size="small" @click="showInput">+ 中转地点</el-button>
					</template>
				</el-form-item>
				<el-form-item label="结束地点" prop="endLocation">
					<el-input v-model="form.endLocation" placeholder="请输入目的地" :disabled="form.carUseType == 2" />
				</el-form-item>
				<el-form-item label="时间" prop="startTime">
					<el-date-picker clearable v-model="form.time" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始时间" end-placeholder="结束时间" @change="timeChange" :disabled="form.carUseType == 2">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="占座数" prop="occupaSeatNum">
					<el-input v-model.number="form.occupaSeatNum" placeholder="请输入占座位数量" />
				</el-form-item>
				<el-form-item label="是否有货物" prop="isGoods">
					<el-select v-model="form.isGoods" placeholder="请选择是否有货物" :disabled="form.carUseType == 2">
						<el-option v-for="dict in dict.type.is_goods" :key="dict.value" :label="dict.label"
							:value="dict.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="货物占座数量" prop="goodsNum" v-if="false">
					<el-input v-model="form.goodsNum" placeholder="请输入货物占座数量" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer" style="text-align: center;">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 修改对话框 -->
		<el-dialog :title="title" :visible.sync="openUp" width="80%" append-to-body>
			<el-form ref="form2" :model="form2" :rules="rules" label-width="80px">
				<el-form-item label="车辆" prop="carId">
					<treeselect v-model="form2.carId" :options="carOptions" :show-count="true" placeholder="请选择车辆" />
				</el-form-item>
				<el-form-item label="司机" prop="driverId">
					<treeselect v-model="form2.driverId" :options="driverOptions" :show-count="true"
						placeholder="请选择司机" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer" style="text-align: center;">
				<el-button type="primary" @click="submitFormUp">确 定</el-button>
				<el-button @click="cancelUp">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		// listApplycar,
		// getApplycar,
		getInfoApply,
		delApplycar,
		// addApplycar,
		updateApplycar,
		// driverTreeSelect,
		// carTreeSelect,
		getDriverList,
		getCarList
	} from '@/api/bpmapply/applycar'
	import {
		listDetails,
		updateDetails
	} from '@/api/bpmusecardetails/details'
	import Treeselect from '@riophae/vue-treeselect'
	import '@riophae/vue-treeselect/dist/vue-treeselect.css'
	import store from '@/store'
	import { parseTime } from '@/utils/ruoyi'
	export default {
		name: 'Applycar',
		dicts: ['is_goods', 'use_car_status', 'is_pin_status'],
		components: {
			Treeselect
		},
		data() {
			return {
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 用车申请表格数据
				applycarList: [],
				// 弹出层标题
				title: '',
				// 是否显示弹出层
				open: false,
				openUp: false,
				// 删除标志时间范围
				daterangeStartTime: [],
				// 删除标志时间范围
				daterangeEndTime: [],
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					carUseType: null,
					licensePlate: null,
					driverName: null,
					startLocation: null,
					endLocation: null,
					startTime: null,
					endTime: null,
					taskStatus: null,
					isGoods: null
				},
				// 表单参数
				form: {},
				form2: {
					time: []
				},
				remainderSeatNum: 6,
				// 表单校验
				rules: {
					carId: [{
						required: true,
						message: '请选择车辆',
						trigger: 'blur'
					}],
					driverId: [{
						required: true,
						message: '请选择司机',
						trigger: 'blur'
					}],
					startLocation: [
						{ required: true, message: '请输入开始地点', trigger: 'blur' },
					],
					endLocation: [
						{ required: true, message: '请输入结束地点', trigger: 'blur' },
					],
					time: [
						{ required: true, message: '请选择时间', trigger: 'blur' },
						{ validator: this.validateTime, trigger: 'blur' },
					],
					occupaSeatNum: [{
							required: true,
							message: '请输入占座数',
							trigger: 'blur'
						},
						{
							type: 'number',
							message: '输入的不是有效数字',
							trigger: 'blur'
						},
						{
							validator: this.validateOccupaSeatNum,
							trigger: 'blur'
						}
					],
				},
				params: {
					detailsId: null // 初始化为 null 或者你需要的默认值
					// 其他的参数属性
				},
				carOptions: [],
				driverOptions: [],
				
				driverHandle: true,
				vehicleHandle: true,
				btnHandle: false,
				row: {}, // 选中行
				dynamicTags: [],
				inputVisible: false,
				inputValue: '',
				roles: []
			}
		},
		created() {
			this.roles = store.getters && store.getters.roles;
			console.log('this.roles', this.roles);
			const detailsCarId = this.$route.params.detailsCarId
			if (detailsCarId !== undefined && detailsCarId !== null) {
				this.queryParams.detailsCarId = detailsCarId
				this.getList()
			} else {
				this.getList()
			}
		},
		methods: {
			/**
			 * 验证占座数量
			 * @param {Object} rule
			 * @param {Object} value
			 * @param {Object} callback
			 */
			validateOccupaSeatNum(rule, value, callback) {
				if (value < 1 || value > this.remainderSeatNum) {
					callback(new Error(`数值必须在1到${this.remainderSeatNum}之间`));
				} else {
					callback();
				}
			},
			/**
			 * 时间修改
			 */
			timeChange(e) {
				console.log('时间修改', e);
				if(e && e.length){
					let startDate = new Date(e[0]);
					startDate.setSeconds(startDate.getSeconds() - 1);
					
					let endDate = new Date(e[1]);
					endDate.setSeconds(endDate.getSeconds() + 1);
					
					let params = {
						id: this.row.id,
						startTime: parseTime(startDate),
						endTime: parseTime(endDate),
					};
					
					this.form.time = e;
					this.form.startTime = e[0];
					this.form.endTime = e[1];
				
					getDriverList(params).then(res => {
						if(res.data.length == 0){
							this.driverHandle = false;
							this.btnHandle = true;
							
							this.$message({
								message: '您好！该时间段目前行政车辆已约满，如您有用车需求请联总裁办车辆负责人 13311170016 进行车辆调配！',
								type: 'warning'
							});
						}else{
							this.driverHandle = true;
							this.btnHandle = false;
							
							getCarList(params).then(res => {
								if(res.data.length == 0){
									this.vehicleHandle = false;
									this.btnHandle = true;
									
									this.$message({
										message: '您好！该时间段目前行政车辆已约满，如您有用车需求请联总裁办车辆负责人 13311170016 进行车辆调配！',
										type: 'warning'
									});
								}else{
									this.vehicleHandle = true;
									this.btnHandle = false;
								}
							});
						}
					});
				}else{
					this.driverHandle = true;
					this.vehicleHandle = true;
					this.btnHandle = false;
				}
			},
			/**
			 * 显示输入框
			 */
			showInput() {
				this.inputVisible = true
				this.$nextTick(() => {
					this.$refs.saveTagInput.$refs.input.focus()
				})
			},
			handleInputConfirm() {
				let inputValue = this.inputValue
				 // 假设限制输入个数为3个
				if (inputValue && this.dynamicTags.length < 9) {
					this.dynamicTags.push(inputValue)
				}
				this.inputVisible = false
				this.inputValue = ''
				this.form.transitPlace = this.dynamicTags
			},
			/**
			 * 跳转详情
			 * @param {Object} id
			 */
			jump(id) {
				this.$router.push(`/bpmapply/applycar/query/${id}`);
			},
			/**
			 * 查询用车申请列表
			 */
			getList() {
				this.loading = true
				this.queryParams.params = {}
				if (null != this.daterangeStartTime && '' != this.daterangeStartTime) {
					this.queryParams.params['beginStartTime'] = this.daterangeStartTime[0]
					this.queryParams.params['endStartTime'] = this.daterangeStartTime[1]
				}
				if (null != this.daterangeEndTime && '' != this.daterangeEndTime) {
					this.queryParams.params['beginEndTime'] = this.daterangeEndTime[0]
					this.queryParams.params['endEndTime'] = this.daterangeEndTime[1]
				}

				listDetails(this.queryParams).then(response => {
					this.applycarList = response.rows || [];
					this.total = response.total
					this.loading = false
				});
			},
			/**
			 * 取消按钮
			 */
			cancel() {
				this.open = false
				this.reset()
			},
			/**
			 * 表单重置
			 */
			reset() {
				this.form = this.initFormData();
				this.form2 = this.initFormData();
				this.resetForm('form');
				this.resetForm('form2');
			},
			/**
			 * 初始化表单数据
			 */
			initFormData() {
				return {
					id: null,
					carUseType: null,
					detailsCarId: null,
					carId: null,
					carName: null,
					driverId: null,
					driverName: null,
					occupaSeatNum: null,
					startLocation: null,
					endLocation: null,
					startTime: null,
					endTime: null,
					taskId: null,
					taskStatus: null,
					isGoods: null,
					goodsNum: null,
					delFlag: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null,
					time: []
				};
			},
			/**
			 * 搜索按钮操作
			 */
			handleQuery() {
				this.queryParams.pageNum = 1
				this.getList()
			},
			/**
			 * 重置按钮操作
			 */
			resetQuery() {
				this.daterangeStartTime = []
				this.daterangeEndTime = []
				this.resetForm('queryForm')
				this.handleQuery()
			},
			/**
			 * 修改司机车辆
			 */
			handleUpdateCarDriver(row) {
				this.row = row;
				this.reset();
				
				this.form2.id = row.id;
				this.form2.carId = row.carId;
				this.form2.driverId = row.driverId;
				
				let params = {
					id: row.id,
					startTime: row.startTime,
					endTime: row.endTime
				};
				
				this.getdriverTree(params);
				this.getcarTree(params);
				
				this.openUp = true
				this.title = '修改车辆司机'
			},
			/**
			 * 修改按钮操作
			 * @param {Object} row
			 */
			handleUpdate(row) {
				this.row = row;
				this.reset();
				
				getInfoApply(row.id).then(response => {
					console.log('通过行程ID获取用车详情', response);
					response.data.time = [
						response.data.startTime,
						response.data.endTime
					];
					
					this.form = response.data;
					this.dynamicTags = this.form.transitPlace || [];
					this.remainderSeatNum = parseInt(row.remainderSeatNum) + parseInt(this.form.occupaSeatNum);
					
					this.open = true;
					this.title = '修改用车申请';
				});
			},
			handleClose(tag) {
				this.form.transitPlace.splice(this.form.transitPlace.indexOf(tag), 1)
			},
			/**
			 * 修改申请
			 */
			submitForm() {
				this.$refs['form'].validate(valid => {
					if (valid) {
						if (this.form.id != null) {
							let params = this.filterateForm(this.form);
	
							if(!this.driverHandle || !this.vehicleHandle){
								this.$message({
									message: '您好！该时间段目前行政车辆已约满，如您有用车需求请联总裁办车辆负责人 13311170016 进行车辆调配！',
									type: 'warning'
								});
							}
							
							if(!this.btnHandle) {
								this.btnHandle = true;
								updateApplycar(params).then(() => {
									this.btnHandle = false;
									this.$modal.msgSuccess('修改成功');
									
									this.cancel();
									this.getList()
								}).catch(err => {
									this.btnHandle = false;
									console.log('修改失败' , err);
								});
							}
						}
					}
				})
			},
			/**
			 * 过滤表单数据
			 * @param {Object} form
			 */
			filterateForm(form){
				let result = {};
				for(let i in form){
					if(form[i] != null && i != 'time'){
						result[i] = form[i];
					}
				}
			
				return result;
			},
			/**
			 * 删除按钮操作
			 * @param {Object} row
			 */
			handleDelete(row) {
				let that = this;
				if(!that.btnHandle){
					that.btnHandle = true;
					
					that.$modal.confirm('是否确认取消并删除该用车申请').then(function() {
						getInfoApply(row.id).then(response => {
							console.log('通过行程ID获取用车详情', response);
							delApplycar(response.data.id).then(() => {
								that.btnHandle = false;
								that.$modal.msgSuccess('取消成功');
								that.getList();
							}).catch(() => {
								that.btnHandle = false;
							});
						}).catch(() => {
							that.btnHandle = false;
						});;
					});
				}
				
			},
			/**
			 * 修改司机和车辆
			 */
			submitFormUp() {
				this.$refs['form2'].validate(valid => {
					if (valid) {
						if(this.form2.carId != this.row.carId || this.form2.driverId != this.row.driverId){
							if (this.form2.id != null && !this.btnHandle) {
								this.btnHandle = true;
								
								updateDetails({
									id: this.form2.id,
									carId: this.form2.carId,
									driverId: this.form2.driverId,
								}).then(() => {
									this.btnHandle = false;
									this.$modal.msgSuccess('修改成功');
									
									this.cancelUp();
									this.getList()
								}).catch(err => {
									this.btnHandle = false;
									console.log('修改失败' , err);
								});
							}
						}else{
							this.cancelUp();
						}
					}
				})
			},
			/**
			 * 取消修改司机和车辆
			 */
			cancelUp() {
				this.openUp = false
			},
			formatTransitPlaces(startLocation, endLocation, transitPlaces) {
				let address = [startLocation];
				if(transitPlaces) address = address.concat(transitPlaces);
				address.push(endLocation);
				
				return address.join(' - ')
			},
			/**
			 * 司机
			 */
			getdriverTree(params) {
				this.driverOptions = [];
			 	getDriverList(params).then(res => {
					res.data.forEach(item => {
						this.driverOptions.push({
							id: item.id,
							label: item.driverName
						});
					});
					
				});
			},
			/**
			 * 车辆
			 */
			getcarTree(params) {
				this.carOptions = [];
				getCarList(params).then(res => {
					res.data.forEach(item => {
						this.carOptions.push({
							id: item.id,
							label: item.licensePlate
						});
					});
				});
			}
		}
	}
</script>